module.exports = Behavior({
    data: {
        host: 'https://flower.yunhuajie.com',
        imgHost: 'https://cdn.yunhuajie.com/',
        userInfo: null,
        allow_jump: true //为false时不可跳转至登录，防止多次跳转
    },
    pageLifetimes: {
        show: function() {
            this.setData({
                userInfo: getApp().globalData.userInfo
            })
        }
    },
    methods: {
        //隐藏弹窗通用方法 
        hide_popup({ currentTarget }) {
            let obj = {};
            obj[currentTarget.dataset.field] = false;
            this.setData(obj)
        },
        /**显示弹窗通用方法 */
        show_popup(e) {
            let obj = {};
            obj[e.currentTarget.dataset.field] = true;
            this.setData(obj)
        },
        //401重定向登录
        redirect_login() {
            if (!this.data.allow_jump) return
            this.data.allow_jump = false
            getApp().globalData.userInfo = null
            this.setData({ userInfo: null })
            wx.removeStorageSync('Authorization')
            wx.stopPullDownRefresh()
            this.jump_login()
        },
        jump_login() {
            let that = this
            wx.navigateTo({
                url: '/pages/login/index',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    login: function() {
                        let options = that.getCurrentPageUrlWithArgs()
                        that.login_reload(options)
                    },
                    setAllow_jump() {
                        if (!that.data.jump_once) that.data.allow_jump = true //jump_once 页面内data 为true时只会跳转一次登录
                    }
                }
            })
        },
        //登录重载方法
        login_reload(options) {
            wx.hideLoading()
            this.onLoad(options)
            this.onShow()
        },
        //登录页获取当前页面的参数
        getCurrentPageUrlWithArgs() {
            const pages = getCurrentPages()
            const currentPage = pages[pages.length - 2]
            return currentPage.options
        },
        //wxml点击跳转
        navigator({ currentTarget }) {
            if (currentTarget.dataset.login) {
                let Authorization = wx.getStorageSync('Authorization');
                if (!Authorization) return this.jump_login()
            }
            wx.navigateTo({ url: currentTarget.dataset.url })
        },
        //延迟执行
        delay(callback, time = 600) {
            let delayTimeId = setTimeout(() => {
                callback()
                clearTimeout(delayTimeId)
            }, time)
        },
        /**
         * 网络请求封装
         * @param {*} req_data  
         * url 请求地址,
         * loadingTip:加载中提示，如果存在，先显示loading
         * login:true 需要登录状态
         * @param {*} success_func 成功回调方法
         * @param {*} fail_func 失败回调方法,code 不为零时也会调用
         * @param {*} complete 最终执行的方法
         */
        request: function(req_data, success_func, fail_func = null, complete = null) {
            let that = this;
            let Authorization = wx.getStorageSync('Authorization');
            if (req_data.login !== false) {
                if (!Authorization) {
                    wx.stopPullDownRefresh()
                    that.redirect_login()
                    complete ? complete() : ''
                    return;
                }
            }

            if (req_data.loadingTip) {
                wx.showLoading({
                    title: req_data.loadingTip,
                    mask: true
                })
            }
            req_data.header = {
                'content-type': 'application/json',
                'Accept': 'application/json, text/javascript, */*; q=0.01'
            };

            if (Authorization) req_data.header.Authorization = Authorization;
            req_data.url = this.data.host + req_data.url

            req_data.success = function(res) { //成功处理
                if (res.statusCode == 200) {
                    if (res.header.Authorization) {
                        wx.setStorage({
                            data: res.header.Authorization,
                            key: 'Authorization',
                        })
                    }
                    let data = res.data;
                    if (data.code === 0) {
                        data.result ? success_func(data.result) : success_func(data)
                    } else {
                        fail_func && fail_func(data)
                        wx.showModal({
                            showCancel: false,
                            content: data.msg || '',
                            confirmColor: '#188075'
                        })
                    }
                } else if (res.statusCode == 401 || res.statusCode == 402) {
                    that.redirect_login()
                } else {
                    fail_func && fail_func(res)
                    wx.showToast({
                        title: res.data || '服务异常',
                        icon: 'none'
                    })
                }
            };
            req_data.fail = function(e) { //失败处理
                fail_func ? fail_func(e) : wx.showToast({
                    title: '网络异常：' + e.errMsg || '',
                    icon: 'none'
                })
            }
            req_data.complete = function(e) { //失败处理
                wx.stopPullDownRefresh()
                req_data.loadingTip && wx.hideLoading()
                complete ? complete(e) : '';
            }
            wx.request(req_data);
        }
    }
})